package com.sure0000.timeServer;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @program: demo
 * @description:
 * @author: xuyouchang@supcon.com
 * @create: 2019-11-04 14:09
 **/
public class TimeClient {
    public static void main(String[] args) {
        EventLoopGroup worker = new NioEventLoopGroup();
        // ServerBootstrap 用于 server 端
        // Bootstrap 用于 client 端
        Bootstrap b = new Bootstrap();

        b.group(worker);

        // NioServerSocketChannel 用于 server 端
        // NioSocketChannel 用于 client 端
        b.channel(NioSocketChannel.class);

        // Server 端使用 childHandler
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new TimeClientHandler());
            }
        });

        // client 没有 parent，所以不能调用 childOption()
        b.option(ChannelOption.SO_KEEPALIVE, true);

        // Server 端使用 bind，Client 端使用 connect
        ChannelFuture future = b.connect("localhost", 8080);
        try {
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
        }
    }
}
